﻿using System.Collections.Generic;
using System.Web;
using System.Configuration;
using NHibernate;

namespace Hasiu.Service
{
    public static class NHibernateHelper
    {
        private const string CurrentSessionKey = "nhibernate.current_session";

        private static readonly ISessionFactory SessionFactory;

        static NHibernateHelper()
        {
            IDictionary<string, string> props = new Dictionary<string, string>();
            props["connection.driver_class"] = "NHibernate.Driver.OleDbDriver";
            props["dialect"] = "NHibernate.Dialect.SybaseDialect";
            props["connection.connection_string"] = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["conn"]);
            props["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
            props["show_sql"] = "false";
            props["adonet.batch_size"] = "10";
            props["use_outer_join"] = "true";
            props["command_timeout"] = "60";
            props["query.substitutions"] = "true 1, false 0, yes 'Y', no 'N'";
            props["proxyfactory.factory_class"] = "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu";
            var cfg = new NHibernate.Cfg.Configuration {Properties = props};
            cfg.AddAssembly("Hasiu.Entity");
            SessionFactory = cfg.BuildSessionFactory();
        }

        /// <summary>
        /// 取得当前Session
        /// </summary>
        /// <returns></returns>
        public static ISession GetCurrentSession()
        {
            var context = HttpContext.Current;
            var currentSession = context.Items[CurrentSessionKey] as ISession;
            if (currentSession == null)
            {
                currentSession = SessionFactory.OpenSession();
                context.Items[CurrentSessionKey] = currentSession;
            }
            currentSession.Clear();
            return currentSession;
        }
    }
}
